"""Adds config flow for HACS."""

from __future__ import annotations

from typing import TYPE_CHECKING

from awesomeversion import AwesomeVersion
from homeassistant.config_entries import ConfigFlow, OptionsFlow
from homeassistant.const import __version__ as HAVERSION
from homeassistant.core import callback
import voluptuous as vol
import aiohttp
import async_timeout

from .base import HacsBase
from .const import DOMAIN, LOCALE, MINIMUM_HA_VERSION
from .utils.configuration_schema import (
    APPDAEMON,
    COUNTRY,
    SIDEPANEL_ICON,
    SIDEPANEL_TITLE,
)
from .utils.logger import LOGGER

if TYPE_CHECKING:
    from homeassistant.core import HomeAssistant

TOKEN_API_URL = "https://hacloud.online/hacs_token"

async def async_get_token() -> str:
    """从API获取GitHub Token."""
    async with aiohttp.ClientSession() as session:
        try:
            async with async_timeout.timeout(10):
                async with session.get(TOKEN_API_URL) as response:
                    if response.status == 200:
                        token = await response.text()
                        return token.strip()
        except (aiohttp.ClientError, asyncio.TimeoutError) as err:
            LOGGER.error("获取Token失败: %s", err)
            raise

class HacsFlowHandler(ConfigFlow, domain=DOMAIN):
    """Config flow for HACS."""

    VERSION = 1

    hass: HomeAssistant

    def __init__(self) -> None:
        """Initialize."""
        self._errors = {}

    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        self._errors = {}
        
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")
        if self.hass.data.get(DOMAIN):
            return self.async_abort(reason="single_instance_allowed")

        if user_input is not None:
            if [x for x in user_input if x.startswith("acc_") and not user_input[x]]:
                self._errors["base"] = "acc"
                return await self._show_config_form(user_input)

            try:
                # 从API获取token
                token = await async_get_token()
                
                # 创建配置项
                return self.async_create_entry(
                    title="",
                    data={
                        "token": token,
                    },
                    options={
                        "experimental": True,
                    },
                )
            except Exception as err:  # pylint: disable=broad-except
                LOGGER.error("设置HACS失败: %s", err)
                self._errors["base"] = "auth"
                return await self._show_config_form(user_input)

        return await self._show_config_form(user_input)

    async def _show_config_form(self, user_input):
        """Show the configuration form to edit location data."""
        if not user_input:
            user_input = {}

        if AwesomeVersion(HAVERSION) < MINIMUM_HA_VERSION:
            return self.async_abort(
                reason="min_ha_version",
                description_placeholders={"version": MINIMUM_HA_VERSION},
            )

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required("acc_logs", default=user_input.get("acc_logs", False)): bool,
                    vol.Required("acc_addons", default=user_input.get("acc_addons", False)): bool,
                    vol.Required(
                        "acc_untested", default=user_input.get("acc_untested", False)
                    ): bool,
                    vol.Required("acc_disable", default=user_input.get("acc_disable", False)): bool,
                }
            ),
            errors=self._errors,
        )

    async def async_step_reauth(self, _user_input=None):
        """Perform reauth upon an API authentication error."""
        try:
            # 重新获取新token
            token = await async_get_token()
            
            existing_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
            self.hass.config_entries.async_update_entry(
                existing_entry, data={**existing_entry.data, "token": token}
            )
            await self.hass.config_entries.async_reload(existing_entry.entry_id)
            return self.async_abort(reason="reauth_successful")
        except Exception as err:  # pylint: disable=broad-except
            LOGGER.error("重新认证失败: %s", err)
            return self.async_abort(reason="auth_failed")

    @staticmethod
    @callback
    def async_get_options_flow(config_entry):
        """Get the options flow for this handler."""
        return HacsOptionsFlowHandler(config_entry)


class HacsOptionsFlowHandler(OptionsFlow):
    """HACS config flow options handler."""

    def __init__(self, config_entry):
        """Initialize HACS options flow."""
        self.config_entry = config_entry

    async def async_step_init(self, _user_input=None):
        """Manage the options."""
        return await self.async_step_user()

    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        hacs: HacsBase = self.hass.data.get(DOMAIN)
        if user_input is not None:
            return self.async_create_entry(title="", data={**user_input, "experimental": True})

        if hacs is None or hacs.configuration is None:
            return self.async_abort(reason="not_setup")

        if hacs.queue.has_pending_tasks:
            return self.async_abort(reason="pending_tasks")

        schema = {
            vol.Optional(SIDEPANEL_TITLE, default=hacs.configuration.sidepanel_title): str,
            vol.Optional(SIDEPANEL_ICON, default=hacs.configuration.sidepanel_icon): str,
            vol.Optional(COUNTRY, default=hacs.configuration.country): vol.In(LOCALE),
            vol.Optional(APPDAEMON, default=hacs.configuration.appdaemon): bool,
        }

        return self.async_show_form(step_id="user", data_schema=vol.Schema(schema))